# !/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import json
import time
from PyQt6.QtWidgets import QDialog
from page.jm_first import Ui_jm_first
from service.tishi_Svc import Tishi     # 提示逻辑
from service.public_Svc import *


# ==============================================================================
# page 4.jm初始化页面
# ==============================================================================


class Jm_first(QDialog, Ui_jm_first):
    """jm初始化识别图页面"""

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.ts = Tishi()  # 提示框

    def jm_first_show(self):
        """获取识别图数据，显示"""
        with open(JM_JSON, 'r', encoding='utf-8') as f:
            data = json.load(f)
            value = data.get('init', {})  # 获取tu数据

        tu1 = value.get('tu1', 0)  # 【清除全部】按钮图
        if tu1 != 0 and os.path.exists(tu1):
            self.label_7.setText("")
            self.label_7.setStyleSheet(f'''
            background-color: rgb(97, 174, 255);
            image:url(./{tu1});''')  # 设置图，相对路径
            self.label_7.show()
        else:
            if 'tu1' in value:  # 如果没图片，则删除图片记录
                del value['tu1']
                with open(JM_JSON, 'w', encoding='utf-8') as f:
                    json.dump(data, f)
        self.spinBox_5.setValue(value.get('coordinate1', (0,0))[0])
        self.spinBox_6.setValue(value.get('coordinate1', (0,0))[1])
        self.checkBox.setChecked(value.get('using_coordinates1', False))


    def init_cut(self):
        """初始化，截取识别图"""
        if activate_window("Apache JMeter"):        # jmeter启动判断
            time.sleep(1)
        else:
            self.ts.xinxi("没找到名称包含【JMeter】的窗口，请检查jmeter是否启动")
            return

        button = self.sender().objectName()  # 获取点击的按钮名称
        region = (self.spinBox_1.value(), self.spinBox_2.value(), self.spinBox_3.value(), self.spinBox_4.value())
        path = f'Identify/init_tu1.png'

        pg.screenshot(path, region=region)      # 坐标+宽+高    # 截图
        if os.path.exists(path):
            data = {f'{button}': path}
            self.jsom_write(data)
            self.jm_first_show()
            self.ts.xinxi("截图保存成功")
        else:
            # 文件不存在
            self.ts.xinxi("截图保存失败")

        activate_window("初始化", max_win=1)

    def save_coordinates(self):
        """保存坐标"""
        button = self.sender().objectName()  # 获取点击的按钮名称
        if button == 'save':
            data = {'coordinate1': (self.spinBox_5.value(), self.spinBox_6.value())}
            self.ts.xinxi("保存成功")
        else:
            data = {'using_coordinates1': self.checkBox.isChecked()}

        self.jsom_write(data)


    def jsom_write(self, data):
        """数据写入json文件"""
        try:
            if not os.path.exists(JM_JSON):
                # 文件不存在，直接写入新数据
                with open(JM_JSON, 'w', encoding='utf-8') as f:
                    json.dump({'init': data}, f)
            else:
                # 文件存在，读取并合并数据
                with open(JM_JSON, 'r', encoding='utf-8') as f:
                    existing_data = json.load(f)
                if 'init' not in existing_data:
                    existing_data['init'] = {}
                existing_data['init'].update(data)
                # 写回更新后的数据
                with open(JM_JSON, 'w', encoding='utf-8') as f:
                    json.dump(existing_data, f)
        except Exception as e:
            self.ts.xinxi(f"写入json文件失败，错误信息：{e}")